<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Shop extends CI_Controller {

    public $render_data;

    function __construct() {
        parent::__construct();
    }

    function add_shop() {

        $this->load->library(array('template', 'carabiner', 'form_validation'));

        $this->render_data['title'] = 'Add your Store (เพิ่มร้านค้า) | ' . WEB_TITLE;

        if ($_POST) {
            if ($this->input->post('tmp_timestamp') == '') {
                redirect('shop/add');
            }
            //Validate//
            $this->form_validation->set_rules('shop_title', 'ชื่อร้านค้า', 'required|max_length[150]|trim');
            $this->form_validation->set_rules('shop_description', 'รายละเอียดร้านค้า', 'required|trim');
            $this->form_validation->set_rules('shop_category', 'หมวดร้านค้า', 'required|trim');
            $this->form_validation->set_rules('shop_link', 'เวบของร้านค้า', 'prep_url|valid_url|trim');
            $this->form_validation->set_rules('shop_facebook', 'เฟจบุ๊คแฟนเพจของร้านค้า', 'prep_url|valid_url|trim');
            $this->form_validation->set_rules('shop_instagram', 'อินสตาแกรมของร้านค้า', 'prep_url|valid_url|trim');
            $this->form_validation->set_rules('shop_level0_cover', 'รูปใบปะหน้าระดับ 1', 'required|min_length[36]|max_length[36]|trim');
            $this->form_validation->set_rules('shop_level0_description', 'คำทักทายใบปะหน้าระดับ 1', 'required|trim');
            $this->form_validation->set_rules('shop_level1_cover', 'รูปใบปะหน้าระดับ 2', 'required|min_length[36]|max_length[36]|trim');
            $this->form_validation->set_rules('shop_level1_description', 'คำทักทายใบปะหน้าระดับ 2', 'required|trim');

            $this->form_validation->set_rules('shop_color', 'สีของใบปะหน้า', 'required|trim');

            $this->form_validation->set_rules('shop_email', 'อีเมล์', 'required|valid_email|trim');
            $this->form_validation->set_rules('shop_password', 'รหัสผ่าน', 'required|min_length[6]|trim');

            if ($this->form_validation->run() != FALSE) {
                // Add to Database //
                $this->load->library('phpass');
                $data_save = array(
                    'shop_title' => strip_tags($this->input->post('shop_title')),
                    'shop_description' => strip_tags($this->input->post('shop_description')),
                    'shop_category' => strip_tags($this->input->post('shop_category')),
                    'shop_link' => strip_tags($this->input->post('shop_link')),
                    'shop_facebook' => strip_tags($this->input->post('shop_facebook')),
                    'shop_instagram' => strip_tags($this->input->post('shop_instagram')),
                    'shop_color' => strip_tags($this->input->post('shop_color')),
                    'shop_level0_cover' => $this->input->post('shop_level0_cover'),
                    'shop_level0_description' => $this->input->post('shop_level0_description'),
                    'shop_level1_cover' => $this->input->post('shop_level1_cover'),
                    'shop_level1_description' => strip_tags($this->input->post('shop_level1_description')),
                    'shop_email' => strip_tags($this->input->post('shop_email')),
                    'shop_password' => $this->phpass->hash($this->input->post('shop_password')),
                    'created_at' => time(),
                );
                $this->db->insert('shops', $data_save);

                $insert_id = $this->db->insert_id();
                // Move tmp to uploads path
                // Create dir from insert_id //
                $crc32_hash = crc32_hash($insert_id);
                mkdir('./uploads/shops/' . $crc32_hash);
                mkdir('./uploads/shops/' . $crc32_hash . '/' . $insert_id);
                copy('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level0_cover')), './uploads/shops/' . $crc32_hash . '/' . $insert_id . '/' . strip_tags($this->input->post('shop_level0_cover')));
                unlink('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level0_cover')));
                copy('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level1_cover')), './uploads/shops/' . $crc32_hash . '/' . $insert_id . '/' . strip_tags($this->input->post('shop_level1_cover')));
                unlink('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level1_cover')));

                // Delete Tmp //
                $this->load->helper('file');
                delete_files('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp'));
                rmdir('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp'));


                $this->load->model('shop_model', 'shop');
                $this->load->library('email');
                $data_save['shop_id'] = $insert_id;
                $data_save['shop_hash'] = hashids_encrypt($insert_id);
                $data_save['shop_password'] = $this->input->post('shop_password');

                // Send Email For Initial Pending //
                $this->email->from(SYSTEM_EMAIL, 'Shopsii Directory');
                $this->email->to(strip_tags($this->input->post('shop_email')));
                $this->email->subject('[Shopsii Registered] - ' . $data_save['shop_title']);

                $this->email->message($this->load->view('email/register', $data_save, TRUE));
                $this->email->send();

                // Send Email Need for Approve to admin //
                $this->email->from(SYSTEM_EMAIL, 'Shopsii Directory');
                $this->email->to(APPROVE_EMAIL);
                $this->email->subject('[Shopsii Need Approve] - ' . $data_save['shop_title']);
                $this->email->message($this->load->view('email/need_approve_register', $data_save, TRUE));
                $this->email->send();




                redirect('shop/' . hashids_encrypt($insert_id));
            }


            $this->render_data['tmp_timestamp'] = $this->input->post('tmp_timestamp');
        } else {
            $this->render_data['show_agreement'] = true;
            $this->render_data['tmp_timestamp'] = time();
        }

        $this->carabiner->js('plupload.js');




        $this->template->write_view('main_nav', 'main_nav', $this->render_data);
        $this->template->write_view('content', 'add_shop', $this->render_data);
        $this->template->render();
    }

    function _check_password($str)
    {
        $this->load->library('phpass');
        if ($this->phpass->check($str, $this->render_data['shop']['shop_password']))
        {
            return TRUE;
        }
        return FALSE;
    }
    
    function edit_shop($shop_hash) {

        $shop_id = hashids_decrypt($shop_hash);
        if (!$shop_id) {

            redirect('/');
        }

        $this->load->library(array('template', 'carabiner', 'form_validation'));

        $this->render_data['title'] = 'Edit your Store (แก้ไขร้านค้า) | ' . WEB_TITLE;

        $this->load->model('shop_model', 'shop');
        $this->render_data['shop'] = $this->shop->get_shop_all_data($shop_id);
        if (!$this->render_data['shop']) {
            redirect('/');
        }

        if ($_POST) {
            if ($this->input->post('tmp_timestamp') == '') {
                redirect('shop/add');
            }
            //Validate//
            $this->form_validation->set_rules('shop_title', 'ชื่อร้านค้า', 'required|max_length[150]|trim');
            $this->form_validation->set_rules('shop_description', 'รายละเอียดร้านค้า', 'required|trim');
            $this->form_validation->set_rules('shop_category', 'หมวดร้านค้า', 'required|trim');
            $this->form_validation->set_rules('shop_link', 'เวบของร้านค้า', 'prep_url|valid_url|trim');
            $this->form_validation->set_rules('shop_facebook', 'เฟจบุ๊คแฟนเพจของร้านค้า', 'prep_url|valid_url|trim');
            $this->form_validation->set_rules('shop_instagram', 'อินสตาแกรมของร้านค้า', 'prep_url|valid_url|trim');
            $this->form_validation->set_rules('shop_level0_cover', 'รูปใบปะหน้าระดับ 1', 'required|min_length[36]|max_length[36]|trim');
            $this->form_validation->set_rules('shop_level0_description', 'คำทักทายใบปะหน้าระดับ 1', 'required|trim');
            $this->form_validation->set_rules('shop_level1_cover', 'รูปใบปะหน้าระดับ 2', 'required|min_length[36]|max_length[36]|trim');
            $this->form_validation->set_rules('shop_level1_description', 'คำทักทายใบปะหน้าระดับ 2', 'required|trim');

            $this->form_validation->set_rules('shop_color', 'สีของใบปะหน้า', 'required|trim');

            $this->form_validation->set_rules('shop_email', 'อีเมล์', 'required|valid_email|trim');
            $this->form_validation->set_rules('shop_password', 'รหัสผ่าน', 'trim|min_length[6]');
            $this->form_validation->set_rules('confirm_password','รหัสผ่านสำหรับเปลี่ยนข้อมูล','callback__check_password');


            if ($this->form_validation->run() != FALSE) {
                // Add to Database //
                $this->load->library('phpass');
                $data_save = array(
                    'shop_title' => strip_tags($this->input->post('shop_title')),
                    'shop_description' => strip_tags($this->input->post('shop_description')),
                    'shop_category' => strip_tags($this->input->post('shop_category')),
                    'shop_link' => strip_tags($this->input->post('shop_link')),
                    'shop_facebook' => strip_tags($this->input->post('shop_facebook')),
                    'shop_instagram' => strip_tags($this->input->post('shop_instagram')),
                    'shop_color' => strip_tags($this->input->post('shop_color')),
                    'shop_level0_cover' => $this->input->post('shop_level0_cover'),
                    'shop_level0_description' => $this->input->post('shop_level0_description'),
                    'shop_level1_cover' => $this->input->post('shop_level1_cover'),
                    'shop_level1_description' => strip_tags($this->input->post('shop_level1_description')),
                    'shop_email' => strip_tags($this->input->post('shop_email')),
                    'modified_at' => time(),
                );

                // Change Password
                if ($this->input->post('shop_password') != '') {
                    $data_save['shop_password'] = $this->phpass->hash($this->input->post('shop_password'));
                }
                
                
                
                $this->db->where('id', $shop_id);
                $this->db->update('shops', $data_save);
                
                if ($this->input->post('shop_password') != '')
                {
                    $this->load->library('email');
                    $data_save['new_password'] = $this->input->post('shop_password');
                    $data_save['shop_hash'] = $shop_hash;
                    // Send Email For Changing Password //
                    $this->email->from(SYSTEM_EMAIL, 'Shopsii Directory');
                    $this->email->to(strip_tags($this->input->post('shop_email')));
                    $this->email->subject('[Shopsii Change Password] - ' . $data_save['shop_title']);
                    
                    $this->email->message($this->load->view('email/change_password', $data_save, TRUE));
                    $this->email->send();
                }

                // Move tmp to uploads path

                $crc32_hash = crc32_hash($shop_id);

                // Check existing in tmp //
                if (is_file('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level0_cover')))) {
                    copy('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level0_cover')), './uploads/shops/' . $crc32_hash . '/' . $shop_id . '/' . strip_tags($this->input->post('shop_level0_cover')));
                    unlink('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level0_cover')));

                    // Delete Old //
                    unlink('./uploads/shops/' . $crc32_hash . '/' . $shop_id . '/' . $this->render_data['shop']['shop_level0_cover']);
                }

                if (is_file('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level1_cover')))) {
                    copy('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level1_cover')), './uploads/shops/' . $crc32_hash . '/' . $shop_id . '/' . strip_tags($this->input->post('shop_level1_cover')));
                    unlink('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp') . '/' . strip_tags($this->input->post('shop_level1_cover')));

                    // Delete Old //
                    unlink('./uploads/shops/' . $crc32_hash . '/' . $shop_id . '/' . $this->render_data['shop']['shop_level1_cover']);
                }
                // Delete Tmp //
                if (is_dir('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp'))) {
                    $this->load->helper('file');
                    delete_files('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp'));
                    rmdir('./uploads/tmp_cover/' . $this->input->post('tmp_timestamp'));
                }



                redirect('shop/' . $shop_hash);
            }

            $this->render_data['tmp_timestamp'] = $this->input->post('tmp_timestamp');
        } else {

            $this->render_data['tmp_timestamp'] = time();
        }

        $this->carabiner->js('plupload.js');


        $this->template->write_view('main_nav', 'main_nav', $this->render_data);
        $this->template->write_view('content', 'edit_shop', $this->render_data);
        $this->template->render();
    }

    public function tmp_cover_upload() {
        $targetDir = FCPATH . 'uploads/tmp_cover/' . $this->input->post('tmp_timestamp');
        $fileName = $this->input->post("name") ? $this->input->post("name") : '';
        $ext = substr(strrchr($fileName, '.'), 1);
        if (!in_array($ext, array('jpg', 'png', 'gif'))) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "File Extension is not an Image."}, "id" : "id"}');
        }
        $saveFile = md5(uniqid()) . '.jpg';
        $savePath = $targetDir . DIRECTORY_SEPARATOR . $saveFile;

        if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {

            // Create target dir
            if (!file_exists($targetDir))
                @mkdir($targetDir);

            // Open temp file
            $out = fopen($savePath, "wb");
            if ($out) {
                // Read binary input stream and append it to temp file
                $in = fopen($_FILES['file']['tmp_name'], "rb");

                if ($in) {
                    while ($buff = fread($in, 4096))
                        fwrite($out, $buff);
                }
                else
                    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                fclose($in);
                fclose($out);
                @unlink($_FILES['file']['tmp_name']);
            }
            else
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }
        else
            die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');


        // Crop Image //
        $level_size = $this->level_size($this->input->post('level'));
        $this->load->library('image_moo');

        $this->image_moo
                ->load($savePath)
                ->resize_crop($level_size[0], $level_size[1])
                ->save($savePath, TRUE);

        die('{"jsonrpc" : "2.0","result":"' . $saveFile . '","id" : "id"}');

        /*
          $this->load->helper('color');
          $color = new GetMostCommonColors();
          $colors = $color->Get_Color($savePath,1);


          // Return JSON-RPC response
          foreach($colors as $key=>$count)
          die('{"jsonrpc" : "2.0", "result" : "' . $saveFile . '", "id" : "id","background":"'.$key.'"}');
         * 
         */
    }

    private function level_size($level) {
        switch ($level) {
            case 0:return array(120, 150);
            case 1:return array(230, 190);
        }
    }

    // Approve Pending //
    public function approve_shop($shop_hash, $admin_hash) {
        $admin_hash = trim($admin_hash);
        $shop_id = hashids_decrypt($shop_hash);
        if ($admin_hash == ADMIN_HASH && $shop_id) {

            $shop = $this->db->select('id as shop_id,shop_title,shop_email,shop_description,shop_category')->where('is_approved', 0)->where('id', $shop_id)->get('shops')->row_array();
            if ($shop) {


                // Send Email 
                $this->load->model('shop_model', 'shop');
                $this->load->library('email');
                // Send Email For Initial Pending //
                $this->email->from(SYSTEM_EMAIL, 'Shopsii Directory');
                $this->email->to($shop['shop_email']);
                $this->email->subject('[Shopsii Approved] - ' . $shop['shop_title']);


                $this->email->message($this->load->view('email/approve_register', $shop, TRUE));
                $this->email->send();

                // Is Approve set to 1
                $this->db->set('is_approved', 1)->set('approved_at', time())
                        ->where('is_approved', 0)->where('id', $shop_id)->update('shops');

                echo 'ได้ทำการอนุมัติร้าน "' . $shop['shop_title'] . '" แล้ว';
            } else {
                echo 'ไม่สามารถอนุมัติได้เนื่องจากไม่พบร้าน หรือ ร้านค้านั้นได้รับการอนุมัติไปแล้ว';
            }
        } else {
            echo 'ไม่สามารถอนุมัติได้เนื่องจากคุณไม่ได้เป็น Admin หรือ หมายเลขร้านค้าไม่ถูกต้อง';
        }
    }

}
